const app = getApp();
var bridgeApi = require('../../utils/bridgeApi.js');
Page({
  data: {
    id: null,
    userId: '',
    userName: '',
    structureTypes: [],
    selectAll: true,
    selectStructureId: '',
    changed: false
  },
  onLoad: function(option) {
    var structureId = '';
    var token = app.globalData.openId;
    
    if (option && option.id) {
      this.setData({
        selectStructureId: option.id
      });
    }

    this.initStructureTypes();
  },
  onReady: function() {
    wx.setNavigationBarTitle({
      title: '结构类型',
    });
  },
  selectType: function(e) {
    if (e.currentTarget.id == "all") {
      // 选择全部类型
      this.setData({
        selectAll: true,
        changed: true
      });
    } else {
      // 选择单个类型
      this.setData({
        selectAll: false,
        changed: true
      });
    }

    var structureTypes = this.data.structureTypes;
    let selectStructure = null;
    for (var i = 0; i < structureTypes.length; i++) {

      if (structureTypes[i].id == e.detail.value) {
        structureTypes[i].checked = true;
        selectStructure = structureTypes[i];
      } else {
        structureTypes[i].checked = false;
      }
    }

    this.setData({
      structureTypes: structureTypes
    });

    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
    prevPage.setData({
      selectStructure: selectStructure
    });
    wx.navigateBack({
      delta: 1
    });
  },
  radioTaped: function(e) {

    if (!this.data.changed) {
      wx.navigateBack({
        delta: 1
      });
    }
  },
  initStructureTypes: function() {
    if (this.data.selectStructureId) {
      this.setData({
        selectAll: false
      });
    } else {
      this.setData({
        selectAll: true
      })
    }

    let structureTypes = wx.getStorageSync("structureTypes");

    if (structureTypes) {
      this.setStructureTypes(structureTypes);
    } else {
      bridgeApi.getStructureTypes().then((data) => {
        this.setStructureTypes(data);
        wx.setStorageSync("structureTypes", data);
      });
    }
  },
  setStructureTypes: function(structureTypes) {
    for (var i = 0; i < structureTypes.length; i++) {
      if (structureTypes[i].id == this.data.selectStructureId) {
        structureTypes[i].checked = true;
      } else {
        structureTypes[i].checked = false;
      }
    }

    this.setData({
      structureTypes: structureTypes
    });
  }
})